package model

import (
	"fmt"
	"gitee.com/liumou_site/logger"
	"regexp"
)

// 格式化占位符正则表达式
var formatSpecifierRegex = regexp.MustCompile(`%[+\-# 0]*[0-9*]*[.[0-9*]*]?[bcdEefgGosqxX%]`)

// LanguageManager 语言管理器
type LanguageManager struct {
	IsChinese       bool
	lastChineseText string
	lastEnglishText string
}

var langManager *LanguageManager

// InitLanguageManager 初始化语言管理器
func InitLanguageManager(isChinese bool) {
	langManager = &LanguageManager{
		IsChinese: isChinese,
	}
}

// GetLanguageManager 获取语言管理器实例
func GetLanguageManager() *LanguageManager {
	if langManager == nil {
		langManager = &LanguageManager{
			IsChinese: false, // 默认为英文
		}
	}
	return langManager
}

// SetLanguage 设置语言
func (lm *LanguageManager) SetLanguage(isChinese bool) {
	lm.IsChinese = isChinese
}

// Info 根据语言输出Info日志
func (lm *LanguageManager) Info(chinese, english string, args ...interface{}) {
	lm.logMessage(logger.Info, chinese, english, args...)
}

// Error 根据语言输出Error日志
func (lm *LanguageManager) Error(chinese, english string, args ...interface{}) {
	lm.logMessage(logger.Error, chinese, english, args...)
}

// Debug 根据语言输出Debug日志
func (lm *LanguageManager) Debug(chinese, english string, args ...interface{}) {
	lm.logMessage(logger.Debug, chinese, english, args...)
}

// Warn 根据语言输出Warn日志
func (lm *LanguageManager) Warn(chinese, english string, args ...interface{}) {
	lm.logMessage(logger.Warn, chinese, english, args...)
}

// logMessage 统一的日志处理内部方法
func (lm *LanguageManager) logMessage(logFunc func(interface{}, ...interface{}), chinese, english string, args ...interface{}) {
	var message string

	if lm.IsChinese {
		if len(args) > 0 {
			if containsFormatSpecifier(chinese) {
				message = fmt.Sprintf(chinese, args...)
			} else {
				message = chinese + fmt.Sprint(args...)
			}
		} else {
			message = chinese
		}
		lm.lastChineseText = message
	} else {
		if len(args) > 0 {
			if containsFormatSpecifier(english) {
				message = fmt.Sprintf(english, args...)
			} else {
				message = english + fmt.Sprint(args...)
			}
		} else {
			message = english
		}
		lm.lastEnglishText = message
	}

	// 直接输出日志消息到标准输出
	logFunc(message)
}

// GetText 根据语言返回最近一次日志输出的文本
func (lm *LanguageManager) GetText() string {
	if lm.IsChinese {
		return lm.lastChineseText
	}
	return lm.lastEnglishText
}

// containsFormatSpecifier 检查字符串是否包含格式化占位符
func containsFormatSpecifier(s string) bool {
	return formatSpecifierRegex.MatchString(s)
}
